<template>
  <div>
    <template>
      <el-input prefix-icon="el-icon-search" v-model="keyword" size="mini" placeholder="输入名字搜索" />
    </template>
    <el-table
      :data="userList | keywordFn(keyword)"
      stripe
      style="width: 100%"
      max-height="800"
      v-loading="loading"
    >
      <el-table-column prop="user_type.type_name" label="角色" width="180"></el-table-column>
      <el-table-column prop="parentCell.name" label="小区" width="180"></el-table-column>
      <el-table-column prop="parentFloor.name" label="楼号" width="180"></el-table-column>
      <el-table-column prop="room" label="房间号" width="180"></el-table-column>
      <el-table-column prop="name" label="名字" width="180"></el-table-column>
      <el-table-column prop="account" label="账号" width="180"></el-table-column>
      <el-table-column prop="phone" label="手机号" width="180"></el-table-column>
      <el-table-column prop="carNumber" label="车位号" width="180"></el-table-column>

      <el-table-column align="right">
        <template slot-scope="scope">
          <el-button
            id="btn-edit"
            icon="el-icon-edit"
            type="primary"
            @click="$router.push(`/userin/edit/${scope.row._id}`)"
          >编辑</el-button>
          <el-button
            icon="el-icon-delete"
            type="danger"
            @click="remove(scope.row)"
            style="margin:5px 0 0 10px"
          >&nbsp;删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userList: [],
      loading: true,
      keyword: ""
    };
  },
  mounted() {
    this.fetchUser();
  },
  methods: {
    //获得用户
    async fetchUser() {
      const user_list = await this.$http.get("rest/user_list");
      this.userList = user_list.data;
      this.loading = false;
    },
    //删除
    async remove(row) {
      this.$confirm(`是否删除?"${row.name}"`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await this.$http.delete(`rest/user/${row._id}`);
        this.$message({
          type: "success",
          message: "删除成功!"
        });
        this.fetchUser();
      });
    }
  },
  //搜索功能实现
  filters: {
    keywordFn(userList, keyword) {
      userList = Array.from(userList);

      keyword = keyword.replace(/\s*/g, "");
      if (userList) {
        if (keyword == "" || keyword == undefined) {
          return userList;
        } else {
          let newUserList;

          newUserList = userList.filter(function(item) {
            if (item.name == keyword) return item;
          });

          return newUserList;
        }
      }
    }//end
    
  }
};
</script>

<style lang="less">
.el-input--mini .el-input__inner {
  height: 38px !important;
}
</style>